package com.dfbz.controller.user;

import com.dfbz.controller.BaseServlet;
import com.dfbz.model.FocusEntity;
import com.dfbz.model.PageEntity;
import com.dfbz.model.User;
import com.dfbz.service.impl.UserDaoServletImp;
import com.dfbz.service.impl.UserServerImpl;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

@WebServlet("/user/*")
public class UserController extends BaseServlet {

    private UserDaoServletImp userDao=new UserDaoServletImp();

    private  UserServerImpl userServer = new UserServerImpl();

    public void findUserMessage(HttpServletRequest req, HttpServletResponse resp) throws Exception{
        Map<String, String> param = getParam(req);
        String realName = param.get("realName");
        Integer currPage;
        if (null==param.get("currPage")){
            currPage=1;
        }else {
            currPage=Integer.parseInt(param.get("currPage"));
        }
        if (realName==null){
            realName="";
        }
        PageEntity<User> pageData = findPage(currPage, realName);
        Integer currPage1 = pageData.getCurrPage();
        Integer totalPage = pageData.getTotalPage();
        Integer startPage=(currPage1-1)/3*3+1;
        Integer endPage=(currPage1-1)/3*3+3;
        if (endPage>totalPage){
            endPage=totalPage;
        }
        pageData.setStartPage(startPage);
        pageData.setEndPage(endPage);
        req.setAttribute("pageData",pageData);
        req.setAttribute("realName",realName);
        Object user = req.getSession().getAttribute("user");
        User user1 = (User) user;
        List<Map<String, Object>> allMyFocus = userDao.getAllMyFocus(user1.getId());
        req.getSession().setAttribute("allMyFocus",allMyFocus);
        req.getRequestDispatcher("/html/user.jsp").forward(req,resp);
    }

    public PageEntity<User> findPage(Integer currPage,String realName){
        PageEntity<User> pageModel = new PageEntity<>();
        pageModel.setCurrPage(currPage);
        Integer pageSize = pageModel.getPageSize();
        Integer startIndex=(currPage-1)*pageSize;
        List<User> data = userDao.fingPage(realName, startIndex, pageSize);
        Integer totalCount = userDao.countByRealName(realName);
        Integer totalPage=totalCount % pageSize ==0 ?totalCount/pageSize :  (totalCount / pageSize) + 1;
        pageModel.setCurrPage(currPage);
        pageModel.setData(data);
        pageModel.setTotalCount(totalCount);
        pageModel.setTotalPage(totalPage);
        return pageModel;
    }

    public void showUserMessage(HttpServletRequest req, HttpServletResponse resp) throws Exception{
        List<Map<String, Object>> allDeptName = userDao.findAllDeptName();
        req.getSession().setAttribute("deptName",allDeptName);
        Object user = req.getSession().getAttribute("user");
        User user1 = (User) user;
        Long id = user1.getId();
        Integer userMessageNum = userDao.findUserMessage(id);
        User byId = userDao.getById(id);
        req.getSession().setAttribute("userMessageNum",userMessageNum);
        req.getSession().setAttribute("user",byId);
        resp.sendRedirect(req.getContextPath()+"/html/user_look.jsp");
    }

    public void updateMessage(HttpServletRequest req, HttpServletResponse resp) throws Exception{
        Map<String, String> param = getParam(req);
        Object user = req.getSession().getAttribute("user");
        User user1 = (User) user;
        user1.setRealName(param.get("realName"));
        user1.setPhone(param.get("phone"));
        user1.setGender(param.get("gender"));
        user1.setAge(Long.parseLong(param.get("age")));
        if (null!=param.get("isSecret")){
            user1.setIsSecret(param.get("isSecret"));
        }else {
            user1.setIsSecret("0");
        }
        userServer.update(user1);
        req.getSession().setAttribute("user",user1);
        resp.sendRedirect(req.getContextPath()+"/html/user_look.jsp");
    }

    public void updatePic(HttpServletRequest req, HttpServletResponse resp) throws Exception{
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setFileSizeMax(1024*1024*1024);
        List<FileItem> fileItems = upload.parseRequest(req);
        String fileName="";
        for (int i = 0; i < fileItems.size(); i++) {
            FileItem fileItem = fileItems.get(i);
            if (!fileItem.isFormField()){
                String name = fileItem.getName();
                String substring = name.substring(name.lastIndexOf("."));
                fileName = UUID.randomUUID().toString() + substring;
                File file = new File("D:\\img\\" + fileName);
                if (!file.exists()){
                    fileItem.write(file);
                }
            }
            String picURL="/img/"+fileName;
            Object user = req.getSession().getAttribute("user");
            User user1 = (User) user;
            user1.setPic(picURL);
            userServer.update(user1);
            req.getSession().setAttribute("user",user1);
        }
    }

    public void getMyFocusUserMessage(HttpServletRequest req, HttpServletResponse resp) throws Exception{
        FocusEntity listFocusEntity = new FocusEntity();
        String userId = req.getParameter("userId");
        String PageNum = req.getParameter("PageNum");
        Integer currPage;
        if (null==PageNum){
            currPage=1;
        }else {
            currPage=Integer.parseInt(PageNum);
        }
        int i = Integer.parseInt(userId);
        Integer totalCount = userDao.findAllMyFocus(i);
        Integer pageSize = listFocusEntity.getPageSize();
        int i1 = totalCount / pageSize;
        Integer totalPage=i1;
        if (totalCount%pageSize>0){
            totalPage+=1;
        }
        listFocusEntity.setCurrPage(currPage);
        listFocusEntity.setTotalCount(totalCount);
        listFocusEntity.setTotalPage(totalPage);
        listFocusEntity.setStartPage((currPage-1)/3*3+1);
        int i3 = (currPage - 1) / 3 * 3 + 3;
        if (i3>totalPage){
            i3=totalPage;
        }
        listFocusEntity.setEndPage(i3);
        int i2 = (listFocusEntity.getCurrPage() - 1) * listFocusEntity.getPageSize();
        List<Map<String, Object>> myFocus = userDao.getMyFocus(i, i2, listFocusEntity.getPageSize());
        listFocusEntity.setData(myFocus);
        req.getSession().setAttribute("myFocus",listFocusEntity);
        req.getRequestDispatcher("/html/my_user.jsp").forward(req,resp);
    }

    public void cancelFocus(HttpServletRequest req, HttpServletResponse resp) throws Exception{
        String userId = req.getParameter("userId");
        String foucsId = req.getParameter("foucsId");
        userDao.cancelFocus(Integer.parseInt(userId),Integer.parseInt(foucsId));
    }

    public void addFocus(HttpServletRequest req, HttpServletResponse resp) throws Exception{
        long userId = Long.parseLong(req.getParameter("userId"));
        long foucsId = Long.parseLong(req.getParameter("foucsId"));
        if (userId==foucsId){
            return;
        }
        userDao.addFocus(userId,foucsId);
    }

    public void userMessage(HttpServletRequest req, HttpServletResponse resp) throws Exception{
        long messageId = Long.parseLong(req.getParameter("MessageId"));
        userDao.addLook(messageId);
        User byId = userDao.getById(messageId);
        Integer befocus = userDao.befocus(messageId);
        req.setAttribute("userMessage",byId);
        req.setAttribute("befocus",befocus);
        req.getRequestDispatcher("/html/user_detail.jsp").forward(req,resp);
    }
}
























